package com.bocai.controller;


import com.bocai.bean.CompetitionHot;
import com.bocai.bean.CustomEvent;
import com.bocai.bean.TCMObject;
import com.bocai.service.ICompetitionService;
import com.bocai.service.ICustomEventService;
import com.bocai.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("competition")
public class CompetitionController {

    @Autowired
    ICompetitionService competitionService;
    @Autowired
    ICustomEventService customEventService;

    @ApiOperation(value = "查询所有热门赛事", notes = "")
    @RequestMapping(value = "allHotCompetition", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "competitionName", dataType = "string", required = false, value = "赛事名称", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionTab", dataType = "string", required = false, value = "赛事标签(格式：1,2,3,4)", defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "isEnable", dataType = "int", required = false, value = "是否禁止（0，启用，1，禁止）", defaultValue = "0"),
    })
    @ResponseBody
    public ResponseData allHotCompetition(String competitionName, String competitionTab, Integer isEnable) {
        ResponseData data = new ResponseData();
        CompetitionHot competitionHot = new CompetitionHot();
        competitionHot.setCompetitionName(competitionName);
        if (competitionTab != null)
            competitionHot.setCompetitionTab("%" + competitionTab + "%");
        if (isEnable != null)
            competitionHot.setIsEnable(isEnable);
        data.setResults(competitionService.selectCompetitionLists(competitionHot));
        data.setCodeEnum(CodeEnum.SUCCESS);

        return data;
    }

    @ApiOperation(value = "设置赛事", notes = "")
    @RequestMapping(value = "setCompetition", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "competitionId", dataType = "int", required = true, value = "赛事id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionName", dataType = "string", required = false, value = "赛事名称", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionTab", dataType = "string", required = false, value = "赛事标签(格式：1,2,3,4)", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "isEnable", dataType = "int", required = false, value = "是否禁止（0，启用，1，禁止）", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData setCompetition(Integer competitionId, String competitionName, String competitionTab, Integer isEnable) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.CODE_1);
        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{competitionId});

        CompetitionHot competitionHot = new CompetitionHot();
        competitionHot.setCompetitionId(competitionId);
        competitionHot.setCompetitionName(competitionName);
        competitionHot.setCompetitionTab(competitionTab);
        competitionHot.setIsEnable(isEnable);

        if (ObjUtils.isNotEmpty(codeEnum)) {
            data.setCodeEnum(CodeEnum.CODE_90001);
            return data;
        }
        if (competitionService.selectHotCompetitionId(competitionId) != null) {
            if (competitionService.updateCompetition(competitionHot) > 0) {
                data.setCodeEnum(CodeEnum.SUCCESS);
            }
        } else {
            if (competitionService.insertCompetition(competitionHot) > 0) {
                data.setCodeEnum(CodeEnum.SUCCESS);
            }
        }
        return data;
    }

    @ApiOperation(value = "获取标签列表", notes = "赛事、比赛、国家")
    @RequestMapping(value = "getTabLists", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tabId", dataType = "int", required = true, value = "标签id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "tabType", dataType = "int", required = true, value = "标签类型（0，赛事 1，比赛，2国家）", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData getTabLists(Integer tabId, Integer tabType) {
        ResponseData data = new ResponseData();
        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{tabId, tabType});
        if (ObjUtils.isNotEmpty(codeEnum)) {
            data.setCodeEnum(CodeEnum.CODE_90001);
            return data;
        }
        if (tabType == 0) {
            CompetitionHot competitionHot = new CompetitionHot();
            competitionHot.setCompetitionTab(tabId + "");
            competitionHot.setIsEnable(0);
            data.setCodeEnum(CodeEnum.SUCCESS);
            data.setResults(competitionService.selectCompetitionLists(competitionHot));
        } else if (tabType == 1) {
            CompetitionHot competitionHot = new CompetitionHot();
            competitionHot.setCompetitionTab(tabId+"");
            competitionHot.setIsEnable(0);
            List<CompetitionHot> lists = competitionService.selectCompetitionLists(competitionHot);
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (int i = 0; i < lists.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> params = new HashMap<>();
                if (null != lists.get(i).getCompetitionId()) {
                    //获取该赛事下的所有比赛并查询是否封禁
                    params.put("competitionId", lists.get(i).getCompetitionId());
                    Long beginTime = System.currentTimeMillis() - 5400 * 1000;
                    Long endTime = System.currentTimeMillis() + 86400 * 1000 * 4;
                    params.put("beginTime", beginTime);
                    params.put("endTime", endTime);
                    params.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
                    params.put("language", SysConstant.LANGUAGE_TYPE);
                    TCMObject object = GetResultUtils.getObject(SysConstant.EVENT_LIST, params);

                    JSONArray jsonArray = object.getBody().getJSONArray("data");
                    //判断赛事下是否有比赛
                    if (jsonArray.size() > 0) {
                        for (int j = 0; j < jsonArray.size(); j++) {
                            JSONObject event = jsonArray.getJSONObject(j);
                            CustomEvent customEvent = customEventService.selectEvent(event.getInt("eventId"));

                            if (customEvent != null && customEvent.getIsEnable() == 1) {
                                jsonArray.remove(j);
                            } else {
                                //获取市场详情
                                Map<String, Object> map1 = new HashMap<>();
                                map1.put("eventId", event.getInt("eventId"));
                                TCMObject tcmObject1 = GetResultUtils.getObject(SysConstant.EVENT_MARKETS, map1);
                                JSONArray markets = null;
                                try{
                                    markets = tcmObject1.getBody().getJSONArray("data");
                                }catch (Exception e){
                                    e.printStackTrace();
                                    continue;
                                }
                                if (null == markets){
                                    continue;
                                }
                                //可以玩的市场个数
                                Integer marketCount = 0;
                                for (int k = 0; k < markets.size(); k++) {
                                    JSONObject market = markets.getJSONObject(k);
                                    Integer ruleType = market.getInt("ruleType");
                                    Integer periodType = market.getInt("periodType");
                                    Integer state = market.getInt("state");

                                    //只算全场的玩法
                                    if (periodType == 100) {
                                        //处理胜平负玩法，并且胜平负市场没有关闭
                                        if (ruleType == 100 && state == 1) {
                                            //判断玩法是否被禁用
                                            if (customEvent != null && customEvent.getRuleTypes().contains(100 + "")) {

                                            } else {
                                                marketCount++;
                                                event.put("market", market);
                                            }
                                        }

                                        //入球单双数
                                        if (ruleType.equals(FootballRuleType.ODD_EVEN.getValue())) {
                                            if (state.equals(MarketState.MarketState_Open.getStatus())) {
                                                if (customEvent != null && customEvent.getRuleTypes().contains(FootballRuleType.ODD_EVEN.getValue() + "")) {

                                                } else marketCount++;
                                            }
                                        }
                                        //正确比分
                                        if (ruleType.equals(FootballRuleType.CORRECT_SCORE.getValue())) {
                                            if (state.equals(MarketState.MarketState_Open.getStatus())) {
                                                if (customEvent != null && customEvent.getRuleTypes().contains(FootballRuleType.CORRECT_SCORE.getValue() + "")) {

                                                } else marketCount++;
                                            }

                                        }

                                        //准确进球数
                                        if (ruleType.equals(FootballRuleType.EXACT_GOALS.getValue())) {
                                            if (state.equals(MarketState.MarketState_Open.getStatus())) {
                                                if (customEvent != null && customEvent.getRuleTypes().contains(FootballRuleType.EXACT_GOALS.getValue() + "")) {

                                                } else marketCount++;
                                            }

                                        }
                                    }
                                    //下一个进球
                                    if (periodType.equals(FootballPeriodType.PeriodType_Dynamic.getValue())) {
                                        if (ruleType.equals(FootballRuleType.NEXT_TEAM_TO_SCORE.getValue()) && state.equals(MarketState.MarketState_Open.getStatus())) {
                                            if (customEvent != null && customEvent.getRuleTypes().contains(FootballRuleType.NEXT_TEAM_TO_SCORE.getValue() + "")) {
                                            } else marketCount++;
                                        }
                                    }
                                }
                                event.put("marketCount", marketCount);
                            }
                        }
                        map.put("competitionName", lists.get(i).getCompetitionName());
                        map.put("competitionId", lists.get(i).getCompetitionId());
                        map.put("events", jsonArray);
                        listMap.add(map);
                    }
                }
            }
            data.setResults(listMap);
        } else if (tabType == 2) {
            CompetitionHot competitionHot = new CompetitionHot();
            competitionHot.setCompetitionTab(tabId + "");
            competitionHot.setIsEnable(0);
            data.setResults(competitionService.selectCountrys(competitionHot));
        } else {
            data.setCodeEnum(CodeEnum.CODE_90002);
        }
        return data;
    }
}
